// @ts-nocheck
export const jsonp = function (url, data, timeout = 5000) {
  return new Promise((resolve, reject) => {
    // 1.初始化url
    const dataString = url.indexOf('?') === -1 ? '?' : '&'
    const callbackName = `jsonpCB_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    url += `${dataString}callback=${callbackName}`
    if (data) {
      // 2.有请求参数，依次添加到url
      for (const k in data) {
        url += `&${k}=${data[k]}`
      }
    }

    const scriptNode = document.createElement('script')
    scriptNode.src = url

    let timeoutId: NodeJS.Timeout | null = null

    const cleanup = () => {
      if (timeoutId) {
        clearTimeout(timeoutId)
        timeoutId = null
      }
      if (window[callbackName]) {
        delete window[callbackName]
      }
      if (document.body.contains(scriptNode)) {
        document.body.removeChild(scriptNode)
      }
    }

    // 3. callback
    window[callbackName] = (result) => {
      cleanup()
      result ? resolve(result) : reject('没有返回数据')
    }

    // 4. 异常情况
    scriptNode.addEventListener(
      'error',
      () => {
        cleanup()
        reject('接口返回数据失败')
      },
      false
    )

    // 5. 超时处理
    timeoutId = setTimeout(() => {
      cleanup()
      reject('请求超时')
    }, timeout)

    // 6. 开始请求
    document.body.appendChild(scriptNode)
  })
}
